import { nullEntity } from '$lib';
import { registerOnHeartBeat } from '$lib/content/heart';
import { Types, defineComponent, type Component, type IWorld, type Entity, hasComponent } from '$lib/ecs';
import { loseBlood } from './blood';

export const BodyPart = {
  bleeding: Types.i32,
  bones: Types.i32,
  bonesMax: Types.i32,
  muscles: Types.i32,
  musclesMax: Types.i32,
  chopped: Types.ui8,
};

const bodyParts: Component[] = [];

export const registerBodyPart = (comp: Component) => {
  bodyParts.push(comp);
  registerOnHeartBeat(comp, (world, e) => {
    const bleeding = comp.bleeding[e];
    if (bleeding > 0) {
      loseBlood(world, e, bleeding);
    }
  });
};

export const enumAllBodyParts = () => {
  return bodyParts;
};

export const enumBodyParts = (world: IWorld, e: Entity) => {
  return enumAllBodyParts().filter((comp) => hasComponent(world, comp, e));
};

export const defineBodyPart = (name: string) => {
  const res = defineComponent(name, BodyPart);
  registerBodyPart(res);
  return res;
};

export const applyBleed = (world: IWorld, e: Entity, bodyPart: Component, amount: number) => {
  bodyPart.bleeding[e] = amount;
};

export const Head = defineBodyPart('Head');
export const Torso = defineBodyPart('Torso');
export const LeftArm = defineBodyPart('LeftArm');
export const RightArm = defineBodyPart('RightArm');
export const LeftLeg = defineBodyPart('LeftLeg');
export const RightLeg = defineBodyPart('RightLeg');
